Reading Progress with Intersection Observer Documentation
This documentation explains a JavaScript code snippet that uses the Intersection Observer API to track and display the reading progress of a post as the user scrolls through it.
Code Overview
const post = document.querySelector(".post");
const progress = document.querySelector("#reading-progress");
let inViewport = false;
let observer = new IntersectionObserver(handler);
function handler(entries, observer) {
entries.forEach(entry => {
if (entry.isIntersecting)
inViewport = true;
else
inViewport = false;
});
}
observer.observe(post);
function getScrollProgress(element) {
let coords = element.getBoundingClientRect();
let height = coords.height;
let progressPercentage = 0;
if (inViewport && coords.top < 0) {
progressPercentage = (Math.abs(coords.top) / height) * 100;
}
return progressPercentage;
}
function showReadingProgress() {
progress.setAttribute("value", getScrollProgress(post));
}
window.onscroll = showReadingProgress;
The
postvariable is assigned a reference to an HTML element with the class "post," representing the post content.The
progressvariable is assigned a reference to an HTML element with the id "reading-progress," which will display the reading progress.The
inViewportvariable is used to track whether the post is currently in the viewport.An
IntersectionObserveris set up with a callback function namedhandler. This callback will be executed when thepostelement enters or exits the viewport.Inside the
handlerfunction, we loop through theentriesarray and set theinViewportvariable based on whether thepostelement is intersecting with the viewport.The
observer.observe(post)line starts observing thepostelement for intersection.The
getScrollProgressfunction calculates the reading progress based on the position of thepostelement in the viewport. It returns a percentage value.The
showReadingProgressfunction updates thevalueattribute of theprogresselement with the reading progress percentage.Finally, the
window.onscrollevent listener triggers theshowReadingProgressfunction as the user scrolls, updating the reading progress.
Usage
To implement reading progress tracking on a post in your project:
Include the JavaScript code within your HTML document.
Ensure you have a post content element with the class "post" and an HTML element with the id "reading-progress" to display the progress.
<progress id="reading-progress" max="100" value="0"></progress>
<article class="post">...lorem ipsum...</article>
As the user scrolls through the post, the reading progress will be displayed in the "reading-progress" element.
You can customize the styling and behavior of the progress indicator as needed.
Conclusion
This Intersection Observer code simplifies the implementation of reading progress tracking as a user scrolls through a post, providing valuable feedback on their progress.